package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录拦截器
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从Cookie中拿token(key值)
        String token = CookieUtil.getToken(request, response);
        //根据token和指定的前缀去redis中拿对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //只有当handler是HandlerMethod的实例化对象
        if (handler instanceof HandlerMethod) {
            //拿到真实类型
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //判断方法上面是否贴有某个注解
            boolean annotation = handlerMethod.hasMethodAnnotation(RequireLogin.class);
            //如果贴有该注解
            if (annotation) {
                //判断是否已登录
                //如果该方法上贴有注解,但是并没有登录,那么就直接跳转登录页面
                if (user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }

        //如果用户已登录,那么每次访问资源都会经过拦截器,那么再次给共享数据设置值,以免关闭浏览器后登录数据丢失
        request.getSession().setAttribute("userInfo",user);
        return true;
    }
}

